/*
 * @Descripttion:
 * @Author: chendingfengmail@163.com
 * @version:
 * @Date: 2021-05-26 16:53:41
 * @LastEditors: Administrator 742573123@qq.com
 * @LastEditTime: 2023-11-11 18:56:54
 */
import {
  Message,
  MessageBox
} from 'element-ui'
import util from '@/libs/util.js'
import router from '@/router'
import Vue from 'vue'
import api from '@/api'

const state = {
  token: "",
  refreshToken: "",
  userInfo: {},
  userRights: [],
  userMenus:[]
}

const getters = {
  userInfo: state => {
    if (!state.userInfo) {
      state.userInfo = util.cookies.get("userInfo");
    }
    return state.userInfo;
  },
  token: state => {
    if (!state.token) {
      state.token = util.cookies.get("token")
    }
    return state.token;
  },
  refreshToken: state => {
    state.refreshToken = util.cookies.get("refreshToken");
    return state.refreshToken;
  },
  userRoleInfo: state => {
    return state.userRights;
  }
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    util.cookies.set("token", token);
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
    util.cookies.set("userInfo", userInfo);
  },
  RESET_TOKEN: (state) => {
    util.cookies.removeAll();
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken;
    util.cookies.set("refreshToken", refreshToken);
  },
  SET_USER_ROLE_INFO: (state, userRoleInfo) => {
    state.userRights = userRoleInfo;
    util.cookies.set("userRoleInfo", userRoleInfo);
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions: {
    /**
     * @description 获取token
     */
    async getToken({ commit, dispatch, state }, userInfo) {
      return await new Promise((resolve, reject) => {
        const { username, password, code, loginType } = userInfo;
        let clientId = util.cookies.get('clientId');
        if (clientId == null) {
          clientId = util.createUniqueString()
          util.cookies.set('clientId', clientId)
        }
        // 获取token
        api.oauth.getToken({ username, password, code, clientId, loginType}).then((res) => {
          if (res.error == 0) {
            commit('SET_TOKEN', res.value.access_token);
            commit('SET_REFRESH_TOKEN', res.value.refresh_token);
            resolve(res.value);
          }
        }).catch((error) => {
          reject(error);
        });
      });
    },

    /**
     * @description 获取用户信息
     */
    async getUserInfoReq({ commit }) {
      return await new Promise((resolve, reject) => {
        api.user.getUserInfo().then((res) => {
          util.cookies.set('uuid', res.value.id)
          commit('SET_USER_INFO', res.value);
          resolve(res.value);
        }).catch((error) => {
          reject(error)
        })
      })
    },

    /**
     * @description 刷新token
     */
    async refreshToken({ commit, dispatch }) {
      let refresh = util.cookies.get("refreshToken");
      return await new Promise((resolve, reject) => {
        api.oauth.refresh(refresh).then((res) => {
          commit('SET_TOKEN', res.value.access_token);
          commit('SET_REFRESH_TOKEN', res.value.refresh_token);
          // dispatch("getUserInfoReq");
          resolve(res.value);
        }).catch((error) => {
          reject(error)
        })
      })
    },

    /**
     * @description 注销用户并返回登录页面
     * @param {Boolean} confirm 是否需要确认
     * @param {Boolean} logoutReq 是否需要发送logout请求
     */
    logout({ commit, dispatch }, { confirm = true, logoutReq = true } = {}) {
      /**
       * @description 注销
       */
      async function logoutReq() {
        // 判断是否需要发送logout请求
        if (logoutReq) {
          await api.oauth.logout().then((res) => {
            // 持久化数据根据cookie中的uuid来区分用户，因此删除cookie需放到最后进行
            // 清空 vuex 用户信息
            dispatch('ddAdmin/user/set', {}, { root: true })
            // 删除全部cookie
            commit('RESET_TOKEN');
            // 跳转路由
            router.push({ name: 'login' })
          })
        } else {
          // 持久化数据根据cookie中的uuid来区分用户，因此删除cookie需放到最后进行
          // 清空 vuex 用户信息
          dispatch('ddAdmin/user/set', {}, { root: true })
          // 删除全部cookie
          commit('RESET_TOKEN');
          // 跳转路由
          router.push({ name: 'login' })
        }
      }

      // 判断是否需要确认
      if (confirm) {
        commit('ddAdmin/gray/set', true, { root: true })
        MessageBox.confirm('确定要注销当前用户吗', '注销用户', { type: 'warning' })
          .then(() => {
            commit('ddAdmin/gray/set', false, { root: true })
            logoutReq()
          })
          .catch(() => {
            commit('ddAdmin/gray/set', false, { root: true })
            Message({ message: '取消注销操作' })
          })
      } else {
        logoutReq()
      }
    },

    /**
     * @description 强制注销
     */
    forcedLogout({ dispatch }) {
      // 设置倒计时时间（s）
      let countdownTime = 3;
      Vue.prototype.$ddMessage({
        dangerouslyUseHTMLString: true,
        message: '<span>登录已失效！ <i id="forced-logout-countdown">3</i> 秒后退回登录界面...</span>',
        type: 'warning',
        duration: countdownTime * 1000,
        onClose: () => {
          dispatch("logout", { confirm: false, logoutReq: false })
        }
      });
      function countdown() {
        countdownTime = countdownTime - 1;
        if(document.getElementById('forced-logout-countdown')){
          document.getElementById('forced-logout-countdown').innerText = countdownTime;
        }
        if (countdownTime <= 0) {
          clearInterval(timer);
        }
      }
      let timer = setInterval(countdown, 1000);
    },

    /**
     * 用户登录
     * @param {username, password, code} userInfo
     */
    async accountLogin({
      commit,
      dispatch,
      state
    }, userInfo) {
      // 获取Token信息
      await dispatch("getToken", userInfo);
      // 获取用户信息
      await dispatch("getUserInfoReq");
      // 设置 vuex 用户信息
      await dispatch("ddAdmin/user/set", state.userInfo, { root: true });
      // 获取用户菜单
      // await dispatch("ddAdmin/menu/getUserMenus", null, { root: true });
      // // 获取用户路由
      // let result = await dispatch("ddAdmin/route/getUserRoutes", null, {root: true});
      // 初始化page路由池
      await dispatch("ddAdmin/page/initOpened", result, {root: true});
      // 初始化字典数据
      // await dispatch("ddAdmin/dict/loadDict", false, {root: true});
    },

    /**
     * 加载全局资源
     * @param {*} param
     */
    async loadResource({ dispatch, commit }) {
    },

    /**
     * @description 用户登录后从持久化数据加载一系列的设置
     * @param {Object} context
     */
    async load({
      dispatch
    }) {
      // 加载用户名
      await dispatch('ddAdmin/user/load', null, {
        root: true
      })
      // 加载主题
      await dispatch('ddAdmin/theme/load', null, {
        root: true
      })
      // 加载页面过渡效果设置
      // await dispatch('ddAdmin/transition/load', null, {
      //   root: true
      // })
      // 持久化数据加载上次退出时的多页列表
      await dispatch('ddAdmin/page/openedLoad', null, {
        root: true
      })
      // 持久化数据加载侧边栏配置
      await dispatch('ddAdmin/menu/asideLoad', null, {
        root: true
      })
      // 持久化数据加载全局尺寸
      await dispatch('ddAdmin/size/load', null, {
        root: true
      })
      // 加载缓存字典数据,false=从接口请求数据，true=获取缓存字典
      // await dispatch("ddAdmin/dict/loadDict", false, {root: true});
    }
  }
}
